<template>
	<video ref="videoPlayer" class="video-js"></video>
</template>
<script setup lang="ts">
	import { ref, reactive, onMounted, onUnmounted } from 'vue'
	import videojs from 'video.js'
	import Player from 'video.js/dist/types/player'
	import 'video.js/dist/video-js.css'
	import 'flv.js'
	import 'videojs-flash'
	import 'videojs-flvjs-es6'

	const MimetypesKind = {
		opus: 'video/ogg',
		ogv: 'video/ogg',
		mp4: 'video/mp4',
		mov: 'video/mp4',
		m4v: 'video/mp4',
		mkv: 'video/x-matroska',
		flv: 'video/x-flv',
		m4a: 'audio/mp4',
		mp3: 'audio/mpeg',
		aac: 'audio/aac',
		caf: 'audio/x-caf',
		flac: 'audio/flac',
		oga: 'audio/ogg',
		wav: 'audio/wav',
		m3u8: 'application/x-mpegURL',
		rtmp: 'rtmp/flv',
	}

	interface propsType {
		url: string
		type: string
		stream?: MediaStream | null
		isautoplays?: boolean
		iscontrols?: boolean //如果需要withDefalut的时候不传，得?: 然后下面也得设置
	}
	const props = withDefaults(defineProps<propsType>(), {
		stream: null,
		isautoplays: true,
		iscontrols: true,
	})

	const videoParameter = reactive({
		autoplay: props.isautoplays,
		language: 'zh-CN',
		controls: props.iscontrols,
		preload: 'auto',
		errorDisplay: true,
		fill: true,
		notSupportedMessage: '此视频暂无法播放，请稍后再试',
		muted: true,
		sources: [
			{
				src: props.url,
				type: MimetypesKind[props.type as keyof typeof MimetypesKind],
			},
		],
	})

	const supportedVideoTypes = Object.keys(MimetypesKind)
	const videoPlayer = ref<HTMLVideoElement | null>(null)
	let player: Player

	const initPlayer = () => {
		console.log(videoParameter)
		if (props.type === 'webrtc' && props.stream) {
			videoPlayer.value!.srcObject = props.stream
			videoPlayer.value!.play()
		} else if (supportedVideoTypes.includes(props.type)) {
			if (videoPlayer.value) {
				player = videojs(videoPlayer.value, videoParameter)
			}
		} else {
			console.error(`Unsupported video type: ${props.type}`)
		}
	}

	onMounted(() => {
		initPlayer()
	})

	onUnmounted(() => {
		if (player) {
			player.dispose()
			player = null
		}
	})
</script>

<style scoped>
	/* Add any custom styling here */
</style>
